package com.gaoxk.zesbFilter;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//@Component
//@WebFilter(urlPatterns = "/ceshifilter/EsbWebService/Maininterface",filterName = "jiekouFilter")
public class ZesbFilter implements Filter{
    private final static Logger logger = LoggerFactory.getLogger(ZesbFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("ZesbFilter 已经初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletRequest httpServletRequest1 = (HttpServletRequest) request;
        logger.info(httpServletRequest.getRequestURL().toString());
        String url = httpServletRequest.getRequestURL().toString();
        //if(url.contains("/ceshifilter/EsbWebService/Maininterface")){
        if(url.contains("/BONDService/cxf") && "POST".equalsIgnoreCase(httpServletRequest.getMethod())){

            logger.info("是cxf");
            //String abc = url.replace("/hzserviec","/test1");
            //logger.info("abc = " +abc);


            //Filter 过滤器拦截修改 Url并且重定向使用

                //logger.info("是post");
               //return ;
                //String test = httpServletRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
                byte[] bytes = readAsBytes(httpServletRequest1);
                String test = new String(bytes, StandardCharsets.UTF_8);
                //ReqMainType reqMainType = new ReqMainType(test);


                String urla= httpServletRequest.getServletPath();
                logger.info(urla);
                if(getServiceId(test).equals("30062000020")){

                httpServletRequest.getRequestDispatcher(urla+"/test1").forward(request, response);}

                //String test = ReadAsChars(httpServletRequest);
                String s = JSONObject.toJSONString(test);
                

                /*try {
                    JAXBContext dcontext = JAXBContext.newInstance(ReqSysHeadType.class);
                    Marshaller marshaller = dcontext.createMarshaller();
                    Unmarshaller unmarshaller = dcontext.createUnmarshaller();


                    //String xml = "<boy><name>David</name></boy>";
                    ReqSysHeadType boy3 = (ReqSysHeadType) unmarshaller.unmarshal(new StringReader(test));
                    logger.info(boy3.getServiceID());
                }catch (Exception e) {
                logger.error("错误", e);
                //return null;
                }*/
               /* MessageFactory msgFactory;
                SOAPMessage reqMsg = null;
                try
                {
                    msgFactory = MessageFactory.newInstance();
                     reqMsg =
                            msgFactory.createMessage(new MimeHeaders(),
                                    new ByteArrayInputStream(test.getBytes(Charset.forName("UTF-8"))));
                    reqMsg.saveChanges();
                    logger.info(reqMsg.getSOAPBody().getAttributeValue("ServiceID"));
                    //return reqMsg;
                }
                catch (Exception e) {
                    logger.error("错误", e);
                    //return null;
                }*/





        }
        else{
            logger.info("不是cxf");

        chain.doFilter(request,response);}
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    // 方法一
    // 二进制读取
    public  byte[] readAsBytes(HttpServletRequest request)
    {

        int len = request.getContentLength();
        byte[] buffer = new byte[len];
        ServletInputStream in = null;

        try
        {
            in = request.getInputStream();

            in.read(buffer, 0, len);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != in)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    //获取serviceID
    public String getServiceId(String filetext){
        String str="";
        Pattern p = Pattern.compile("(?<=\\ServiceID>)[^\\</]+");
        Matcher m = p.matcher(filetext);
        while (m.find()){
            String str2 = m.group(0);
            if (str2 !=null && !"".equals(str2)){
                str2 = str2.replace("\r\n","");
                if(str2 !=null && !"".equals(str2) && str2.trim() !=null && !"".equals(str2.trim())){
                    str = str2;
                }
            }
        }
        return str;
    }




}
